package services

import (
	"chat/global"
	"chat/internal/models/dao"
	"gorm.io/gorm"
)

func CreateUser(user dao.User) error {
	return global.Db.Create(&user).Error
}

func GetUserInfo(mobile string) (user dao.User, err error) {
	err = global.Db.Where("mobile = ?", mobile).First(&user).Error
	return
}

func CreateUser2(user2 dao.User2) error {
	return global.Db.Create(&user2).Error
}

func GetUserInfo2(name string) (user2 dao.User2, err error) {
	err = global.Db.Where("name = ?", name).First(&user2).Error
	return
}

func PublishUpdates(update dao.Update) error {
	return global.Db.Create(&update).Error
}

func UpdatesList(content string, page, pageSize int) (list []*dao.Update, err error) {
	err = global.Db.Where("content like ?", "%"+content+"%").Order("l_count desc").Scopes(Paginate(page, pageSize)).Find(&list).Error
	return list, err
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

func SubscribeFollow(follow dao.Follow) error {
	return global.Db.Create(&follow).Error
}

func UpdatesLList(content string, userId, page, pageSize int) (list []*dao.Update, err error) {
	err = global.Db.Where("content like ?", "%"+content+"%").Where("user_id = ?", userId).Scopes(Paginate2(page, pageSize)).Find(&list).Error
	return list, err
}

func Paginate2(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

func SpotLikes(likes dao.Likes) error {
	return global.Db.Create(&likes).Error
}

func Del(userId int, types string) error {
	var user dao.Likes
	return global.Db.Where("user_id = ?", userId).Where("types = ?", types).Delete(&user).Error
}

func LeaveComment(comment dao.Comment) error {
	return global.Db.Create(&comment).Error
}

func CommentDel(userId int, types string) error {
	var user dao.Comment
	return global.Db.Where("user_id = ?", userId).Where("types = ?", types).Delete(&user).Error
}

func UpdateDel(userId int) error {
	var user dao.Update
	return global.Db.Where("user_id = ?", userId).Delete(&user).Error
}

func CreateGroup(group dao.Group) error {
	return global.Db.Create(&group).Error
}

func DelGroup(groupId, leaderId int) error {
	var user dao.Group
	return global.Db.Where("group_id = ?", groupId).Where("leader_id = ?", leaderId).Delete(&user).Error
}

func CreatePull(pull dao.Pull) error {
	return global.Db.Create(&pull).Error
}

func CreateMember(member dao.Member) error {
	return global.Db.Create(&member).Error
}

func DelMember(userId int) error {
	var user dao.Member
	return global.Db.Where("user_id = ?", userId).Delete(&user).Error
}
